<template>
  <view class="page">
    <view class="form">
      <!-- 商品图片 -->
      <view class="form-item">
        <text class="label">商品图片</text>
        <view class="image-upload">
          <view class="image-preview" v-if="form.image" @click="chooseImage">
            <image class="preview-img" :src="form.image" mode="aspectFill"></image>
            <view class="image-overlay">
              <text class="overlay-text">点击更换</text>
            </view>
          </view>
          <view class="image-placeholder" v-else @click="chooseImage">
            <text class="placeholder-icon">📷</text>
            <text class="placeholder-text">点击上传图片</text>
          </view>
        </view>
      </view>

      <!-- 商品名称 -->
      <view class="form-item">
        <text class="label">商品名称 <text class="required">*</text></text>
        <input 
          class="input" 
          v-model="form.name" 
          placeholder="请输入商品名称"
          maxlength="100"
        />
      </view>

      <!-- 分类选择 -->
      <view class="form-item">
        <text class="label">商品分类 <text class="required">*</text></text>
        <picker 
          mode="selector" 
          :range="categories" 
          range-key="name"
          :value="categoryIndex"
          @change="onCategoryChange"
        >
          <view class="picker">
            {{ selectedCategory || '请选择分类' }}
            <text class="picker-arrow">›</text>
          </view>
        </picker>
      </view>

      <!-- 价格 -->
      <view class="form-item">
        <text class="label">销售价格 <text class="required">*</text></text>
        <view class="input-group">
          <text class="input-prefix">¥</text>
          <input 
            class="input" 
            v-model="form.price" 
            type="digit"
            placeholder="0.00"
          />
        </view>
      </view>

      <!-- 原价 -->
      <view class="form-item">
        <text class="label">原价</text>
        <view class="input-group">
          <text class="input-prefix">¥</text>
          <input 
            class="input" 
            v-model="form.originalPrice" 
            type="digit"
            placeholder="0.00"
          />
        </view>
      </view>

      <!-- 库存 -->
      <view class="form-item">
        <text class="label">库存数量 <text class="required">*</text></text>
        <input 
          class="input" 
          v-model="form.stock" 
          type="number"
          placeholder="请输入库存数量"
        />
      </view>

      <!-- 商品描述 -->
      <view class="form-item full">
        <text class="label">商品描述</text>
        <textarea 
          class="textarea" 
          v-model="form.description" 
          placeholder="请输入商品描述"
          maxlength="500"
        ></textarea>
      </view>

      <!-- 上架状态 -->
      <view class="form-item switch-item">
        <text class="label">立即上架</text>
        <switch :checked="form.status === 1" @change="toggleStatus" color="#667eea"/>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-bar">
      <view class="btn-cancel" @click="goBack">取消</view>
      <view class="btn-save" @click="saveProduct">保存</view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      productId: null,
      form: {
        name: '',
        categoryId: null,
        image: '',
        price: '',
        originalPrice: '',
        stock: '',
        description: '',
        status: 1
      },
      categories: [],
      categoryIndex: 0,
      submitting: false
    }
  },
  computed: {
    selectedCategory() {
      if (this.form.categoryId && this.categories.length > 0) {
        const category = this.categories.find(c => c.id === this.form.categoryId)
        return category ? category.name : ''
      }
      return ''
    }
  },
  onLoad(options) {
    if (options.id) {
      this.productId = options.id
      uni.setNavigationBarTitle({
        title: '编辑商品'
      })
      this.loadProductDetail()
    } else {
      uni.setNavigationBarTitle({
        title: '新增商品'
      })
    }
    
    this.loadCategories()
  },
  methods: {
    async loadCategories() {
      try {
        const { getCategoryList } = require('@/api/category')
        const list = await getCategoryList()
        this.categories = list || []
        
        // 如果有默认分类，选中第一个
        if (!this.productId && this.categories.length > 0) {
          this.form.categoryId = this.categories[0].id
          this.categoryIndex = 0
        }
      } catch (error) {
        console.error('加载分类失败:', error)
      }
    },
    
    async loadProductDetail() {
      try {
        uni.showLoading({ title: '加载中...' })
        
        const { getProductDetail } = require('@/api/product')
        const product = await getProductDetail(this.productId)
        
        this.form = {
          name: product.name,
          categoryId: product.categoryId,
          image: product.image,
          price: product.price,
          originalPrice: product.originalPrice || '',
          stock: product.stock,
          description: product.description || '',
          status: product.status
        }
        
        // 设置分类索引
        if (this.form.categoryId && this.categories.length > 0) {
          const index = this.categories.findIndex(c => c.id === this.form.categoryId)
          if (index !== -1) {
            this.categoryIndex = index
          }
        }
        
        uni.hideLoading()
      } catch (error) {
        console.error('加载商品详情失败:', error)
        uni.hideLoading()
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      }
    },
    
    chooseImage() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          // 上传到服务器
          this.uploadImage(res.tempFilePaths[0])
        }
      })
    },
    
    uploadImage(filePath) {
      uni.showLoading({ title: '上传中...' })
      
      uni.uploadFile({
        url: 'https://xindian66.xyz/api/file/upload',
        filePath: filePath,
        name: 'file',
        formData: {
          module: 'product/image'  // 商品图片模块
        },
        header: {
          'ss_satoken': uni.getStorageSync('ss_satoken') || ''
        },
        success: (res) => {
          try {
            const data = JSON.parse(res.data)
            if (data.code === 0) {
              // 上传成功，保存服务器返回的URL
              this.form.image = data.data.url
              uni.hideLoading()
              uni.showToast({
                title: '图片上传成功',
                icon: 'success'
              })
            } else {
              console.error('图片上传失败:', data.msg)
              uni.hideLoading()
              uni.showToast({
                title: data.msg || '上传失败',
                icon: 'none'
              })
            }
          } catch (e) {
            console.error('解析响应失败:', e)
            uni.hideLoading()
            uni.showToast({
              title: '上传失败',
              icon: 'none'
            })
          }
        },
        fail: (error) => {
          console.error('图片上传失败:', error)
          uni.hideLoading()
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          })
        }
      })
    },
    
    onCategoryChange(e) {
      const index = e.detail.value
      this.categoryIndex = index
      this.form.categoryId = this.categories[index].id
    },
    
    toggleStatus(e) {
      this.form.status = e.detail.value ? 1 : 0
    },
    
    async saveProduct() {
      // 校验
      if (!this.form.name) {
        uni.showToast({ title: '请输入商品名称', icon: 'none' })
        return
      }
      
      if (!this.form.categoryId) {
        uni.showToast({ title: '请选择商品分类', icon: 'none' })
        return
      }
      
      if (!this.form.price || parseFloat(this.form.price) <= 0) {
        uni.showToast({ title: '请输入正确的价格', icon: 'none' })
        return
      }
      
      if (!this.form.stock || parseInt(this.form.stock) < 0) {
        uni.showToast({ title: '请输入正确的库存', icon: 'none' })
        return
      }
      
      if (this.submitting) return
      
      this.submitting = true
      uni.showLoading({ title: '保存中...' })
      
      try {
        const { saveProduct } = require('@/api/product')
        
        const params = {
          name: this.form.name,
          categoryId: this.form.categoryId,
          image: this.form.image,
          price: parseFloat(this.form.price),
          originalPrice: this.form.originalPrice ? parseFloat(this.form.originalPrice) : null,
          stock: parseInt(this.form.stock),
          description: this.form.description,
          status: this.form.status
        }
        
        if (this.productId) {
          params.id = this.productId
        }
        
        await saveProduct(params)
        
        uni.hideLoading()
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        })
        
        // 设置刷新标记
        const pages = getCurrentPages()
        if (pages.length > 1) {
          const prevPage = pages[pages.length - 2]
          if (prevPage.$vm) {
            prevPage.$vm.needRefresh = true
          }
        }
        
        setTimeout(() => {
          uni.navigateBack()
        }, 1500)
      } catch (error) {
        console.error('保存商品失败:', error)
        uni.hideLoading()
        uni.showToast({
          title: error.message || '保存失败',
          icon: 'none'
        })
      } finally {
        this.submitting = false
      }
    },
    
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20rpx;
  padding-bottom: 180rpx;
}

.form {
  background: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
}

.form-item {
  display: flex;
  align-items: center;
  padding: 28rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  
  &.full {
    flex-direction: column;
    align-items: flex-start;
  }
  
  &.switch-item {
    justify-content: space-between;
  }
  
  &:last-child {
    border-bottom: none;
  }
}

.label {
  font-size: 28rpx;
  color: #333;
  width: 160rpx;
  flex-shrink: 0;
  
  .required {
    color: #ff4d4f;
  }
}

.input {
  flex: 1;
  font-size: 28rpx;
  color: #333;
}

.input-group {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 8rpx;
  
  .input-prefix {
    font-size: 28rpx;
    color: #999;
  }
}

.textarea {
  width: 100%;
  min-height: 120rpx;
  font-size: 28rpx;
  color: #333;
  margin-top: 20rpx;
}

.picker {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 28rpx;
  color: #333;
  
  .picker-arrow {
    font-size: 48rpx;
    color: #999;
  }
}

/* 图片上传 */
.image-upload {
  flex: 1;
}

.image-preview {
  width: 200rpx;
  height: 200rpx;
  border-radius: 12rpx;
  overflow: hidden;
  position: relative;
  
  .preview-img {
    width: 100%;
    height: 100%;
  }
  
  .image-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    opacity: 0;
    transition: opacity 0.3s;
    
    .overlay-text {
      font-size: 24rpx;
      color: #fff;
    }
  }
  
  &:active .image-overlay {
    opacity: 1;
  }
}

.image-placeholder {
  width: 200rpx;
  height: 200rpx;
  border: 2rpx dashed #ddd;
  border-radius: 12rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
  background: #fafafa;
  
  .placeholder-icon {
    font-size: 64rpx;
  }
  
  .placeholder-text {
    font-size: 22rpx;
    color: #999;
  }
}

/* 底部按钮 */
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #fff;
  padding: 24rpx;
  box-shadow: 0 -4rpx 12rpx rgba(0, 0, 0, 0.05);
  display: flex;
  gap: 24rpx;
  z-index: 100;
}

.btn-cancel,
.btn-save {
  flex: 1;
  height: 88rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  font-weight: bold;
}

.btn-cancel {
  background: #f5f5f5;
  color: #666;
}

.btn-save {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
}
</style>

